package com.yangy.flvdemo.ffmpeg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 *
 * 监听用户连接数据
 *
 * @author YangYuan
 * @date 2024/7/3
 */
public class NginxConnectionMonitor {

    private static Logger log = LoggerFactory.getLogger(NginxConnectionMonitor.class);
    private static final String NGINX_STATUS_URL = "http://10.0.0.110:8080/stream_status";  // Nginx HTTP状态接口地址
    private RTSPToFLVStreamer streamer;  // RTSP到FLV推流器实例


    public NginxConnectionMonitor(RTSPToFLVStreamer streamer) {
        this.streamer = streamer;
    }

    public void startMonitoring(String streamName) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    int connectionCount = getActiveConnections(streamName);
                    log.info("Active connections: " + connectionCount);

                    // If no active connections, stop streaming
                    if (connectionCount <= 1) {
                        streamer.stopStreaming();
                        timer.cancel();  // Stop the timer
                        VideoStreamerBucket.removeStreamer(streamName);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 5000, 5000);  // 每5秒查询一次连接状态
    }

    private int getActiveConnections(String streamName) throws IOException {
        URL url = new URL(NGINX_STATUS_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        int connectionCount = 0;
        boolean isLive = false;

        while ((line = reader.readLine()) != null) {
            if (line.contains(streamName)) {
                isLive = true;
            }
            if (isLive && line.contains("<nclients>")){
                String replace = line.replace("<nclients>", "")
                        .replace("</nclients>", "");
                connectionCount += Integer.parseInt(replace.trim());
                isLive = false;
                //跳出循环
                break;
            }
        }

        reader.close();
        return connectionCount;
    }
}
